<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          :loading="isLoading"
          loading-text="正在登录中..."
          round
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  name: 'MyLogin',
  data () {
    return {
      info: {
        mobile: '13912345678',
        code: '246810'
      },
      isLoading: false,
      rules: {
        mobile: [
          // required:必须要填，message：不满足弹出的提示
          { required: true, message: '请填写手机号' },
          // 加一条用正则校验是不是手机号的规则
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      this.isLoading = true
      // js里面无法调用$route取值方法 所有把index里需要back的路径在vue里取到 然后赋值
      this.info.back = this.$route.query.back
      // 异步代码 等待完成再继续往下执行
      // dispatch 返回的是一个promise对象 可以.then
      await this.$store.dispatch('user/login', this.info)
      // 不管成功还是失败都要关掉加载状态
      this.isLoading = false
    }
  }
}
</script>

<style></style>
